package wgmcu

import (
	"ac"
	log "ac-common-go/glog"
	"ac-julink/rpcagent"
	"ac-julink/tool/config"
	"git.apache.org/thrift.git/lib/go/thrift"
	"net"
	"strconv"
	"time"
)

var thriftPoolManager *rpcagent.ThriftPoolManager

func dial(ip, port string, connTimeout time.Duration) (*rpcagent.IdleClient, error) {
	tSocket, err := thrift.NewTSocketTimeout(net.JoinHostPort(ip, port), connTimeout)
	if err != nil {
		log.Errorf("connect to wgota error")
		return nil, err
	}
	if err := tSocket.Open(); err != nil {
		return nil, err
	}
	transport := thrift.NewStreamTransportFactory(tSocket, tSocket, true).GetTransport(tSocket)
	//	transport := thrift.NewTTransportFactory().GetTransport(tSocket)
	//	transport := thrift.NewTBufferedTransportFactory(1024).GetTransport(tSocket)
	protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()

	client := NewDUSServiceClientFactory(transport, protocolFactory)
	return &rpcagent.IdleClient{Socket: tSocket, Client: client, CreateTime: time.Now()}, nil
}
func close(c *rpcagent.IdleClient) error {
	err := c.Socket.Close()
	return err
}

var httpProxy *rpcagent.Proxy

func InitTriftPool() {
	ip := config.GetConfigValue("WGNS", "http_dus_ip")
	if ip == "" {
		log.Errorf("http_dus_ip is not valid!!")
		return
	}
	httpPort := config.GetConfigValue("WGNS", "http_dus_port")
	if httpPort == "" {
		log.Errorf("http_dus_port is not valid!!")
		return
	}

	maxConnsPerHost, ok := config.GetConfigIntValue("WGNS", "http_dus_maxconnsPerHost")
	if !ok {
		maxConnsPerHost = rpcagent.DEFAULTMAXCONNSPERHOST
	}

	respHeaderTimeout, ok := config.GetConfigIntValue("WGNS", "http_dus_response_header_timeout")
	if !ok {
		respHeaderTimeout = rpcagent.DEFAULTRESPHEASERTIMEOUT
	}
	idleTimeout, ok := config.GetConfigIntValue("WGNS", "http_dus_idletimeout")
	if !ok {
		idleTimeout = rpcagent.DEFAULTIDLETIME
	}
	retryNum, ok := config.GetConfigIntValue("WGNS", "http_dus_retrynum")
	if !ok {
		retryNum = rpcagent.DEFAULTRETRYNUM
	}

	httpProxy = rpcagent.NewProxy(ip, httpPort, maxConnsPerHost, respHeaderTimeout, idleTimeout, retryNum, true)
	log.Infof("CTL http pool init success!")
}

type HttpCommonResp struct {
	ResultCode int32 `json:"resultCode"`
}

type FeedbackUpgradeResultHttpReq struct {
	WifiId    string `json:"wifiid"`
	Ver       string `json:"subSysVersion"`
	Type      string `json:"subSysCode"`
	ErrorCode string `json:"resCode"`
}

func FeedbackUpgradeResultHttp(wifiid string, _type string, _ver string, _errCode int) (err error) {
	log.Infof("Rpc call ReportDeviceCmdresult ==>>%s", wifiid)
	reqctx := ac.NewZContext("", "", 0, 0, "", "zc-julink")

	req := FeedbackUpgradeResultHttpReq{
		WifiId:    wifiid,
		Ver:       _ver,
		Type:      _type,
		ErrorCode: strconv.Itoa(_errCode),
	}
	var resp HttpCommonResp
	if err := httpProxy.DirectCall(reqctx, "feedback_upgrade_result", "POST", "", &req, &resp); err != nil {
		log.Warningf("ReportDeviceCmdresult call feedback_upgrade_result: err[%v]", err)
		return err
	}
	return nil
}
